package top.szhome.framework.starter.boot.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.szhome.framework.core.tools.exception.SzhomeException;
import top.szhome.framework.core.tools.support.Resp;

import java.util.stream.Collectors;

/**
 * 异常拦截
 *
 * @author 唐加利
 * @date 2023/2/10
 **/
@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {

    /**
     * 默认异常
     * @param throwable
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public Resp handle(Throwable throwable){
        log.error("发生未知异常", throwable);
        return Resp.fail("500", "发生未知异常，" + throwable.toString());
    }

    /**
     * 参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Resp handle(MethodArgumentNotValidException e){
        log.error("参数校验未通过", e);
        String message = e.getBindingResult()
                .getAllErrors()
                .stream()
                .map(error -> error.getDefaultMessage())
                .collect(Collectors.joining("；"));
        return Resp.fail("5001", "参数校验未通过：" + message);
    }

    /**
     * 业务异常
     * @param e 业务异常
     * @return
     */
    @ExceptionHandler(SzhomeException.class)
    public Resp handle(SzhomeException e){
        log.error("请求处理失败", e);
        return Resp.fail(e.getCode(), e.getMessage());
    }

}
